package com.gray.wow.freemarker;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FreemarkerUtil {
	private static FreemarkerUtil fu=null;
	public FreemarkerUtil() {}
	
	public static FreemarkerUtil getInstance(){
		if(fu==null) fu=new FreemarkerUtil();
		return fu;
	}
	
	public Template getTemplate(String name){
		try {
			Configuration cfg=new Configuration();
			cfg.setDefaultEncoding("UTF-8");
			cfg.setOutputEncoding("UTF-8");
			cfg.setClassForTemplateLoading(this.getClass(), "/ftl");
			Template temp=cfg.getTemplate(name);
			return temp;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public void filePrint(String name,Map<String, Object> root,String outFile){
		FileWriter out=null;
		try {
			out=new FileWriter(new File(outFile));
			Template temp=this.getTemplate(name);
			temp.process(root, out);
		} catch (IOException e) {
			e.printStackTrace();
		}catch (TemplateException e) {
			e.printStackTrace();
		}finally{
			try {
				if(out!=null)out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
}
